//
//  AppDelegate.m
//  QiYReader
//
//  Created by 奇阅科技 on 14-11-15.
//  Copyright (c) 2014年 奇阅科技. All rights reserved.
//

#import "AppDelegate.h"
#import "UMessage.h"
#import "UMSocial.h"
#import "UMSocialSinaHandler.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialConfig.h"
#import "MBProgressHUD.h"
#import "ZMYLKDB.h"
#import "ZMYNetWorkAPI.h"
#import "MobClick.h"
#import "ZMYVersionNotes.h"

@interface AppDelegate ()<UIAlertViewDelegate>
@property (strong,nonatomic) NSString * upDateUrl;
@property (strong,nonatomic) NSString * releaseVersionText;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     [NSThread sleepForTimeInterval:1.5];
    
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    [UMessage startWithAppkey:@"54410033fd98c51e87003d9e" launchOptions:launchOptions];
    [UMSocialData setAppKey:@"54410033fd98c51e87003d9e"];
    [UMSocialSinaHandler openSSOWithRedirectURL:kAppRedirectURI];
    [UMSocialWechatHandler setWXAppId:@"wxbbeb6670a5e7f7d8" appSecret:@"7a583e7fe31ecf7129d6900d165c8c40" url:kAppRedirectURI];
    [UMSocialQQHandler setQQWithAppId:QQAppKey appKey:@"VmV0nc7mBeKI8Fra" url:kAppRedirectURI];
    [UMSocialQQHandler setSupportWebView:YES];
    //    [UMSocialData openLog:YES];

    BOOL isFirst = [[NSUserDefaults standardUserDefaults]boolForKey:@"fistRun"];
    if (isFirst) {
        //不是第一次启动
        self.window.rootViewController = [[UIStoryboard storyboardWithName:@"BookRack" bundle:Nil]instantiateInitialViewController];
    }else{
        self.window.rootViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"MainViewController"];
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"fistRun"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
//    else {
//        if ([[[ZMYNetWorkAPI default] createEngine]isReachable]) {
//            [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"isFirst"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//        } else {
//            self.window.rootViewController = [[UIStoryboard storyboardWithName:@"BookRack" bundle:Nil]instantiateInitialViewController];
//        }
//    }
    [self setUMessage];
    NSDictionary *plistDic = [[NSBundle mainBundle] infoDictionary];
    NSString *channelName = [plistDic objectForKey:@"ChannelName"];
    [UMessage setChannel:channelName]; //推送渠道设置
    //友盟统计
    [MobClick startWithAppkey:@"54410033fd98c51e87003d9e" reportPolicy:BATCH channelId:channelName];
    [MobClick setAppVersion:XcodeAppVersion];
    [self updateAppVersion];
    [[ZMYNetWorkAPI default]getYiDongFromID:^(NSDictionary *resultDic) {
        
    } error:^(NSString *errorStr) {
        NSLog(@"%@",errorStr);
    }];
    return YES;
}
-(void)updateAppVersion{
    __weak typeof(self) weakSelf = self;
    [ZMYVersionNotes isAppVersionUpdatedWithAppIdentifier:@"940984461" updatedInformation:^(NSString *releaseNoteText, NSString *releaseVersionText, NSDictionary *resultDic) {
        UIAlertView *createUserResponseAlert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"已更新版本:%@",releaseVersionText] message:releaseNoteText delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [createUserResponseAlert show];
    } latestVersionInformation:^(NSString *releaseNoteText, NSString *releaseVersionText, NSDictionary *resultDic) {
        if (![[NSUserDefaults standardUserDefaults] boolForKey:releaseVersionText]&&resultDic) {
            UIAlertView *createUserResponseAlert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"有新的版本:%@",releaseVersionText] message:releaseNoteText delegate:weakSelf cancelButtonTitle:@"立即下载" otherButtonTitles: @"忽略此版本", @"下次再说",nil];
            weakSelf.upDateUrl = [resultDic objectForKey:@"trackViewUrl"];
            weakSelf.releaseVersionText = releaseVersionText;
            createUserResponseAlert.tag = 1001;
            [createUserResponseAlert show];
        }
    } completionBlockError:^(NSError *error) {
        NSLog(@"An error occurred: %@", [error localizedDescription]);
    }];
}
-(void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 1001) {
        switch (buttonIndex) {
            case 0:
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.upDateUrl]];
                break;
            case 1:
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:self.releaseVersionText];
                [[NSUserDefaults standardUserDefaults] synchronize];
                break;
                
            default:
                break;
        }
    }
}
-(void)setUMessage{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        //register remoteNotification types
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
#else
    //register remoteNotification types
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
#endif
//    [UMessage setLogEnabled:YES];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                  stringByReplacingOccurrencesOfString: @">" withString: @""]
                 stringByReplacingOccurrencesOfString: @" " withString: @""]);
    [UMessage registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [UMessage didReceiveRemoteNotification:userInfo];
}
-(void)goToBookRack{
    self.window.rootViewController = nil;
    self.window.rootViewController = [[UIStoryboard storyboardWithName:@"BookRack" bundle:Nil]instantiateInitialViewController];
    [self.window makeKeyAndVisible];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [UMSocialSnsService  applicationDidBecomeActive];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [UMSocialSnsService handleOpenURL:url];
}
+ (AppDelegate *)delegate {
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}
+ (MBProgressHUD *)showHUDAndHide:(NSString *)str view:(UIView *)view {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.removeFromSuperViewOnHide = YES;
    hud.mode =MBProgressHUDModeText;
    hud.detailsLabelText = str;
    [hud hide:YES afterDelay:1.8];
    hud.removeFromSuperViewOnHide=YES;
    return hud;
}
+ (MBProgressHUD *)showwarnHUDAndHide:(NSString *)str view:(UIView *)view{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:view];
    [view addSubview:hud];
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"LoadFail.png"]];
    hud.mode = MBProgressHUDModeCustomView;
    hud.labelText = str;
    hud.removeFromSuperViewOnHide=YES;
    ;
    hud.labelFont = [UIFont systemFontOfSize:12];
    [hud show:YES];
    [hud hide:YES afterDelay:1.8];
    return hud;
    
}
+ (MBProgressHUD *)showHUD:(NSString *)str view:(UIView *)view {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.removeFromSuperViewOnHide = YES;
    hud.detailsLabelText = str;
    return hud;
}
+ (void)hideAllHUD:(UIView *)view {
    [MBProgressHUD hideAllHUDsForView:view animated:YES];
}
+ (void)showAlert:(NSString *)title message:(NSString *)msg {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}
@end
